#pragma once
#include <iostream>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <strings.h>
#include <unistd.h>
#include "nocopy.hpp"
#include "Comm.hpp"
#include "InetAddr.hpp"

const static int16_t defaultport = 8888;
const static int defaultfd = -1;
const static int defaultsize = 1024;

class UdpServer : public nocopy
{
public:
    UdpServer(int16_t port = defaultport) : _port(port), _fd(defaultfd)
    {
    }
    void Init()
    {
        _fd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_fd < 0)
        {
            exit(Socket_Err);
        }

        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;
        int n = bind(_fd, (sockaddr *)&local, sizeof(local));
        if (n != 0)
        {
            exit(Bind_Err);
        }
    }

    void Start()
    {
        char buffer[defaultsize];

        while (true)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int n = recvfrom(_fd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                buffer[n] = 0;
                InetAddr addr(peer);
                std::cout <<"["<<addr.PrintDebug()<<"]" <<"say# " << buffer << std::endl;
                sendto(_fd, buffer, sizeof(buffer), 0, (struct sockaddr *)&peer, len);
            }
        }
    }
    ~UdpServer() 
    {
        close(_fd);
    }

private:
    int16_t _port;
    int _fd;
};
